package com.caption.auth.secuity.handler;

import com.alibaba.fastjson.JSONObject;
import com.caption.auth.secuity.entity.SysUserDetails;
import com.caption.core.local.LocalUser;
import com.caption.core.properties.SignProperties;
import com.caption.core.utils.JwtUtils;
import com.caption.core.utils.ResponseUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @description: 认证成功处理类
 * @author: 码农
 * @date: 2021-12-31 19:51:35
 */
@Component
public class UserAuthSuccessHandler implements AuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        SysUserDetails sysUserDetails = (SysUserDetails) authentication.getPrincipal();
        LocalUser localUser = new LocalUser();
        BeanUtils.copyProperties(sysUserDetails, localUser);
        String content = JSONObject.toJSONString(localUser);
        String token = JwtUtils.createToken(localUser.getId(), SignProperties.jwtSignKey, content, 600);
        Map<String,Object> resultData = new HashMap<>();
        resultData.put("code","200");
        resultData.put("msg", "登录成功");
        resultData.put("token",token);
        ResponseUtils.out(response,resultData);
    }
}
